package com.hkunderground.blog;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.hkunderground.blog.helper.ConstantHelper;
import com.hkunderground.blog.helper.UtilityHelper;

public class AddEntryServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

   private static final Logger log = Logger.getLogger(AddEntryServlet.class.getName());

   public void doGet(HttpServletRequest req, HttpServletResponse resp)  throws IOException
   { 
	   this.doPost(req, resp);
   }//doGet
   
   
	 public void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws IOException 
     {
		  UserService userService = UserServiceFactory.getUserService();
	      User user = userService.getCurrentUser();

	      if (user == null) 
	      {
	        	resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
	      }//user = null
	      
          String lsContent = req.getParameter(ConstantHelper.PARA_CONTENT);
          String lsTitle = req.getParameter(ConstantHelper.PARA_TITLE);
          String lsDate = req.getParameter(ConstantHelper.PARA_DATE);
          String[] lsTagArr = req.getParameterValues(ConstantHelper.PARA_TAG);

          DatastoreService loDatastore = DatastoreServiceFactory.getDatastoreService();
	        	
	      log.info("user nick -> "+ user.getNickname()+" user id -> "+user.getUserId()+" user eMail -> "+user.getEmail());
	            
	      //the kind of key, the name of key
	      Key loBlogKey = KeyFactory.createKey(ConstantHelper.KEY_KIND_BLOG, ConstantHelper.KEY_NAME_BLOG_HKUG);
	      Date loDate = UtilityHelper.getDateFromMMMMDDYYYY_24H(lsDate);
	      Entity loBlogEntity = new Entity(ConstantHelper.ENTITY_BLOG, loBlogKey);
	      loBlogEntity.setProperty(ConstantHelper.E_BLOG_USER, user);	            
	      loBlogEntity.setProperty(ConstantHelper.E_BLOG_TITLE, lsTitle);		         
	      loBlogEntity.setProperty(ConstantHelper.E_BLOG_DATE, loDate);
	      loBlogEntity.setProperty(ConstantHelper.E_BLOG_CONTENT, lsContent);

	      //save blog
	      loDatastore.put(loBlogEntity);
	            
	       //handle tag
          if (lsTagArr != null)
          {
  
       	    for (String lsTag : lsTagArr)
        	{
       	    	lsTag = lsTag.trim();
       	    	String lsUpperTag = lsTag.toUpperCase();
       	    	if ("".equals(lsTag))
       	    	{
       	    		continue;
       	    	}//if trim
       	    	
 
       	       	//tag 
            	Key loTagKey = KeyFactory.createKey(ConstantHelper.KEY_KIND_TAG, ConstantHelper.KEY_NAME_TAG);
           	    Query loTagQuery = new Query(ConstantHelper.ENTITY_TAG);
       	    	
       	    	loTagQuery.addFilter(ConstantHelper.E_TAG_UPPER_NAME, Query.FilterOperator.EQUAL, lsUpperTag);
       	    	PreparedQuery lpgTagQuery = loDatastore.prepare(loTagQuery);
       	    	
       	    	Entity loTag = lpgTagQuery.asSingleEntity();
       	  
                //save to blog_tag entity
                //save blog_tag id to blog
                
       	        //if new tag save it
                if (loTag == null)
       	    	{
       	    	  Entity leTagEntity = new Entity(ConstantHelper.ENTITY_TAG, loTagKey);
       	    	  leTagEntity.setProperty(ConstantHelper.E_TAG_NAME, lsTag);	            
       	    	  leTagEntity.setProperty(ConstantHelper.E_TAG_UPPER_NAME, lsUpperTag);		         
       		
       		      //save tag
       		      loDatastore.put(leTagEntity);
       		      loTag=leTagEntity;
       	    	}//tag = null
        
          	    //Tag Blog Rel
            	//Key lkBlogTagRel = KeyFactory.createKey(ConstantHelper.KEY_KIND_BLOG_TAG_REL, ConstantHelper.KEY_NAME_BLOG_TAG_REL);
                
                //Entity leBlogTagRel = new Entity(ConstantHelper.ENTITY_BLOGTAG_REL, lkBlogTagRel);
          	  	
                Entity leBlogTagRel = new Entity(ConstantHelper.ENTITY_BLOGTAG_REL, loBlogEntity.getKey());
 
          	    //leBlogTagRel.setProperty(ConstantHelper.E_BLOGTAG_REL_BLOG_KEY, loBlogKey);
          	    leBlogTagRel.setProperty(ConstantHelper.E_BLOGTAG_REL_TAG_KEY, loTag.getKey());
         	    
     		   //save blog_tag_rel
     		   loDatastore.put(leBlogTagRel);
        	          		
        	}//for lsTag
        	  
          }//if (lsTagArr != null)

	      
	      
	      resp.sendRedirect("/viewEntry.jsp");
	                
     }//doGet
	
}//BlogServlet